package com.hanhai.zrb.api.mongodb;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.ArrayUtils;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class BeanUtil {

	/**
	 * 把实体bean对象转换成DBObject
	 */
	public static <T> DBObject bean2DBObject(T bean)
	 {
		if (bean == null) {
			return null;
		}
		DBObject dbObject = new BasicDBObject();
		// 获取对象对应类中的所有属性域
		Field[] fields = bean.getClass().getDeclaredFields();
		//父类的属性
		Field[] parentFields=bean.getClass().getSuperclass().getDeclaredFields();
		//合并
		Field[] allFeilds=(Field[]) ArrayUtils.addAll(fields, parentFields);
		for (Field field : allFeilds) {
			// 获取属性名
			String varName = field.getName();
			// 修改访问控制权限
			boolean accessFlag = field.isAccessible();
			if (!accessFlag) {
				field.setAccessible(true);
			}
			Object param;
			try {
				param = field.get(bean);
				if (param == null) {
					continue;
				} else if (param instanceof Integer) {// 判断变量的类型
					int value = ((Integer) param).intValue();
					dbObject.put(varName, value);
				} else if (param instanceof String) {
					String value = (String) param;
					dbObject.put(varName, value);
				} else if (param instanceof Double) {
					double value = ((Double) param).doubleValue();
					dbObject.put(varName, value);
				} else if (param instanceof Float) {
					float value = ((Float) param).floatValue();
					dbObject.put(varName, value);
				} else if (param instanceof Long) {
					long value = ((Long) param).longValue();
					dbObject.put(varName, value);
				} else if (param instanceof Boolean) {
					boolean value = ((Boolean) param).booleanValue();
					dbObject.put(varName, value);
				} else if (param instanceof Date) {
					Date value = (Date) param;
					dbObject.put(varName, value);
				}
				// 恢复访问控制权限
				field.setAccessible(accessFlag);
			} catch (IllegalArgumentException | IllegalAccessException e) {
				e.printStackTrace();
			}
			
		}
		return dbObject;
	}

	/**
	 * 把DBObject转换成bean对象
	 */
	public static <T> T dbObject2Bean(DBObject dbObject, T bean) {
		if (bean == null) {
			return null;
		}
		Field[] fields = bean.getClass().getDeclaredFields();
		Field[] parentFields=bean.getClass().getSuperclass().getDeclaredFields();
		Field[] allFeilds=(Field[]) ArrayUtils.addAll(fields, parentFields);
		for (Field field : allFeilds) {
			String varName = field.getName();
			Object object = dbObject.get(varName);
			if (object != null) {
				try {
					BeanUtils.setProperty(bean, varName, object);
				} catch (IllegalAccessException | InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
		return bean;
	}
}